#include "leveleditorview.h"
#include "document.h"
#include "gameObjects/visualobject.h"
#include "gameObjects/actor.h"
#include "levelObjects/levelactor.h"
#include "levelObjects/level.h"
#include "modes/leveleditormode.h"
#include "openGL/openglrenderer.h"
#include <gl/GLU.h>
#include "openGL/orbitalcamera.h"

using namespace LevelModeWidgets;

LevelEditorView::LevelEditorView(QPointer<Modes::LevelEditorMode> lem, QWidget *parent)
	: QGLWidget(QGLFormat(QGL::SampleBuffers), parent)
	, m_levelEditorMode(lem)
{
	setAutoFillBackground(false);
	setMouseTracking(true);
	OpenGLRenderer::instance().init(this);
	m_camera = OrbitalCamera(Vec3(0, 0, 2000), Vec3(0, 0, 0));
}

void LevelEditorView::initializeGL()
{
	glClearColor(0.0, 0.0, 0.0, 0.0);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_MULTISAMPLE);
}

void LevelEditorView::resizeGL(int width, int height)
{
	setupViewport(width, height);
}

void LevelModeWidgets::LevelEditorView::paintEvent( QPaintEvent* )
{
	makeCurrent();
	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadIdentity();
	m_camera.apply();

	setupViewport(width(), height());

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	QPointer<LevelObjects::Level> level = qobject_cast<LevelObjects::Level*>(m_levelEditorMode->selectedLevel());

	if(level)
	{
		const LevelObjects::Level::LevelActors& levelActors = level->levelActors();

		foreach(QPointer<LevelObjects::AbstractLevelObject> lo, levelActors)
		{
			QRect rect;
			QImage image;
			QPointer<LevelObjects::LevelActor> loActor = qobject_cast<LevelObjects::LevelActor*>(lo);
			rect = loActor->actorVisualData(image);

			if(loActor->isSelected())
			{
				glColor4f(1, 1, 0, 1);
			}
			else
			{
				glColor4f(1, 1, 1, 1);
			}

			OpenGLRenderer::instance().drawQuadSprite(image,
				QPointF(0, 0), 0.0f, QPointF(1.0f, 1.0f), rect);
		}
	}

	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();

	QPainter painter(this);
	painter.end();
}

void LevelModeWidgets::LevelEditorView::setupViewport( int width, int height )
{
	int side = qMin(width, height);
	glViewport((width - side) / 2, (height - side) / 2, side, side);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	//glOrtho(-500.5, +500.5, -500.5, +500.5, 0.0, 15.0);
	gluPerspective(45, (float)width/(float)height, 0, 1);
	glMatrixMode(GL_MODELVIEW);
}

void LevelModeWidgets::LevelEditorView::mousePressEvent( QMouseEvent *event )
{
	m_prevMousePos = event->pos();
}

void LevelModeWidgets::LevelEditorView::mouseMoveEvent( QMouseEvent *event )
{
	QPoint pos = event->pos();
	QPointF offset = pos - m_prevMousePos;

	if(event->buttons() & Qt::LeftButton)
	{
		m_camera.rotate(offset);
		update();
	}
	else if(event->buttons() & Qt::RightButton)
	{
		m_camera.zoom(-offset.y());
		update();
	}

	m_prevMousePos = event->pos();
}

void LevelModeWidgets::LevelEditorView::mouseReleaseEvent( QMouseEvent *event )
{

}
